<script setup>
import useConfigStore from "@/store/modules/config.js";
import { useRouter } from 'vue-router'
import { getCodeImg } from '@/api/login'
import { decrypt, encrypt } from '@/utils/jsencrypt'
import useUserStore from '@/store/modules/user'
import CookieUtil from '@/utils/cookieUtil.js'

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()
const title = import.meta.env.VITE_APP_TITLE
const loginForm = ref({
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: '',
})

const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
}

const codeUrl = ref('')
const loading = ref(false)
// 验证码开关
const captchaEnabled = ref(true)
// 注册开关
const register = ref(false)
const redirect = ref(undefined)
const configStore = useConfigStore()

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

onMounted(() => {
  console.log(configStore.configData)
})
function handleLogin() {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        CookieUtil.setCookie('username', encodeURIComponent(loginForm.value.username), 30)
        CookieUtil.setCookie('password', encrypt(loginForm.value.password), 30)
        CookieUtil.setCookie('rememberMe', loginForm.value.rememberMe, 30)
      }
      else {
        // 否则移除
        CookieUtil.deleteCookie('username')
        CookieUtil.deleteCookie('password')
        CookieUtil.deleteCookie('rememberMe')
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        const query = route.query
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== 'redirect') {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
        router.push({ path: redirect.value || '/', query: otherQueryParams })
      }).catch(() => {
        loading.value = false
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode()
        }
      })
    }
  })
}

function getCode() {
  getCodeImg().then((res) => {
    const data = res.data
    captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = `data:image/gif;base64,${data.img}`
      loginForm.value.uuid = data.uuid
    }
  })
}

function getCookie() {
  const username = CookieUtil.getCookie('username')
  const password = CookieUtil.getCookie('password')
  const rememberMe = CookieUtil.getCookie('rememberMe')
  loginForm.value = {
    username: username === null ? loginForm.value.username : username,
    password: password === null ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe),
  }
}

getCode()
getCookie()
</script>

<template>
  <div class="bg-global-bg flex flex-col">
    <div class="logo fixed top-2 left-5 flex-y-center">
      <img src="@/assets/logo/logo.png" class="w-15 h-15">
      <div class="relative top-1 left-3 text-[18px] text-[#1648FF] font-bold">
        {{ title }}
      </div>
    </div>
    <div class="flex-1 flex items-center justify-center">
      <div class="login-card flex rounded-md shadow-sm ">
        <div class="flex-1 h-full hidden md:inline-block">
          <img src="@/assets/images/login-image.png" class="max-h-[500px]">
        </div>
        <el-card class="box-card" shadow="never">
          <!--          <div class="title font-bold mb-5 text-global-text"> -->
          <!--            欢迎登录 -->
          <!--          </div> -->
          <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form mx-5 mt-11">
            <div class="text-center mb-7 text-2xl font-bold text-global-text login-form-title">
              <!--              {{ title }} -->
              账户登录
            </div>
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                type="text"
                size="large"
                auto-complete="off"
                placeholder="账号"
              >
                <template #prefix>
                  <svg-icon name="user" class="el-input__icon input-icon" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                size="large"
                auto-complete="off"
                placeholder="密码"
                show-password
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <svg-icon name="password" class="el-input__icon input-icon" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="captchaEnabled" prop="code">
              <el-input
                v-model="loginForm.code"
                size="large"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <svg-icon name="validCode" class="el-input__icon input-icon" />
                </template>
              </el-input>
              <div class="login-code ml-2">
                <img :src="codeUrl" class="login-code-img" @click="getCode">
              </div>
            </el-form-item>
            <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">
              记住密码
            </el-checkbox>
            <el-form-item class="w-full mt-3">
              <el-button
                :loading="loading"
                size="large"
                type="primary"
                class="w-full"
                @click.prevent="handleLogin"
              >
                <span v-if="!loading" class="text-[16px]">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
              <div v-if="register" style="float: right;">
                <router-link class="link-type" to="/register">
                  立即注册
                </router-link>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<style lang='scss' scoped>
.bg-global-bg{
  background-image: url("../assets/images/logo-bg.png");
  min-height: 100vh;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
.login-code {
  width: 33%;
  height: 39px;
  float: right;
  //position: relative;
  //bottom: 4px;
  img {
    cursor: pointer;
    vertical-align: middle;
    height: 100%;
  }
}
:deep(.el-input){
  height: 41px;
}
.box-card{
  .title{
    position: relative;
    &::after{
      position: absolute;
      left: -13px;
      content: "";
      display: block;
      height: 18px;
      background-color: var(--el-color-primary);
      width: 5px;
      border-radius: 6px;
      top: 2px;
    }
  }
  .login-form-title{
    position: relative;
    &::after{
      position: absolute;
      content: "";
      display: block;
      height: 5px;
      background-color: var(--el-color-primary);
      width: 30px;
      border-radius: 6px;
      bottom: -10px;
      left: 46%;
    }
  }
}
</style>
